const Role = require('../model/mongo/role.model');
const Permission = require('../model/mongo/permission.model');

// 获取角色列表
const getRoles = async (ctx) => {
  try {
    const { page = 1, limit = 10, name, status } = ctx.query;
    const query = {};

    if (name) {
      query.name = new RegExp(name, 'i');
    }
    if (status !== undefined) {
      query.status = parseInt(status);
    }

    const roles = await Role.find(query)
      .populate('permissions')
      .skip((page - 1) * limit)
      .limit(parseInt(limit))
      .sort({ sort: 1, createdAt: -1 });

    const total = await Role.countDocuments(query);

    ctx.body = {
      code: 200,
      data: {
        list: roles,
        total,
        page: parseInt(page),
        limit: parseInt(limit)
      },
      message: '获取成功'
    };
  } catch (error) {
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: '服务器错误'
    };
  }
};

// 创建角色
const createRole = async (ctx) => {
  try {
    const { name, code, description, permissions, status, sort } = ctx.request.body;

    // 检查角色名是否已存在
    const existingRole = await Role.findOne({ name });
    if (existingRole) {
      ctx.status = 400;
      ctx.body = {
        code: 400,
        message: '角色名已存在'
      };
      return;
    }

    // 检查角色编码是否已存在
    const existingCode = await Role.findOne({ code });
    if (existingCode) {
      ctx.status = 400;
      ctx.body = {
        code: 400,
        message: '角色编码已存在'
      };
      return;
    }

    // 检查权限是否存在
    if (permissions && permissions.length > 0) {
      const permissionsExist = await Permission.find({ _id: { $in: permissions } });
      if (permissionsExist.length !== permissions.length) {
        ctx.status = 400;
        ctx.body = {
          code: 400,
          message: '部分权限不存在'
        };
        return;
      }
    }

    const role = await Role.create({
      name,
      code,
      description,
      permissions,
      status,
      sort
    });

    ctx.body = {
      code: 200,
      data: role,
      message: '创建成功'
    };
  } catch (error) {
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: '服务器错误'
    };
  }
};

// 更新角色
const updateRole = async (ctx) => {
  try {
    const { id } = ctx.params;
    const { name, code, description, permissions, status, sort } = ctx.request.body;

    const role = await Role.findById(id);
    if (!role) {
      ctx.status = 404;
      ctx.body = {
        code: 404,
        message: '角色不存在'
      };
      return;
    }

    // 检查角色名是否已存在
    if (name && name !== role.name) {
      const existingRole = await Role.findOne({ name });
      if (existingRole) {
        ctx.status = 400;
        ctx.body = {
          code: 400,
          message: '角色名已存在'
        };
        return;
      }
    }

    // 检查角色编码是否已存在
    if (code && code !== role.code) {
      const existingCode = await Role.findOne({ code });
      if (existingCode) {
        ctx.status = 400;
        ctx.body = {
          code: 400,
          message: '角色编码已存在'
        };
        return;
      }
    }

    // 检查权限是否存在
    if (permissions && permissions.length > 0) {
      const permissionsExist = await Permission.find({ _id: { $in: permissions } });
      if (permissionsExist.length !== permissions.length) {
        ctx.status = 400;
        ctx.body = {
          code: 400,
          message: '部分权限不存在'
        };
        return;
      }
    }

    const updatedRole = await Role.findByIdAndUpdate(
      id,
      {
        name,
        code,
        description,
        permissions,
        status,
        sort
      },
      { new: true }
    ).populate('permissions');

    ctx.body = {
      code: 200,
      data: updatedRole,
      message: '更新成功'
    };
  } catch (error) {
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: '服务器错误'
    };
  }
};

// 删除角色
const deleteRole = async (ctx) => {
  try {
    const { id } = ctx.params;

    const role = await Role.findById(id);
    if (!role) {
      ctx.status = 404;
      ctx.body = {
        code: 404,
        message: '角色不存在'
      };
      return;
    }

    await Role.findByIdAndDelete(id);

    ctx.body = {
      code: 200,
      message: '删除成功'
    };
  } catch (error) {
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: '服务器错误'
    };
  }
};

module.exports = {
  getRoles,
  createRole,
  updateRole,
  deleteRole
}; 